<template>
  <div>
    <div v-if="isPageShow" class="wrap">
      <!-- header头部 -->
      <!-- <m-header
        :backcolor="'#1968FA'"
        :color="'#fff'"
        opacity="1"
        hocolor="#fff"
        filter="blur(0px)"
      ></m-header> -->
      <div style="height: 50px"></div>
      <div class="container" style="width: 100%; max-width: 1200px">
        <div class="content">
          <div class="right-box">
            <!-- menu栏 -->
            <m-Menu activeDefault="2"></m-Menu>
            <!--  -->
          </div>
          <div class="left-box" v-loading="$store.state.isLoading">
            <div class="top">
              <div class="title">
                <div style="display: flex; align-items: center">
                  <i
                    class="el-icon-back"
                    style="font-size: 30px; margin-right: 10px; cursor: pointer"
                    @click="$router.push('/personalcenter')"
                  ></i>
                  <span style="margin-right: 20px">{{
                    `${className} (${totalCount})人`
                  }}</span
                  ><a @click="handleOpenModifyInfo('修改班级信息')"
                    >修改班级信息</a
                  >
                </div>
                <span>
                  <i
                    class="el-icon-circle-plus"
                    style="color: #1968fa; margin: 0px 5px"
                  ></i>
                  <a
                    @click="handleOpenModifyStudent(true)"
                    style="color: #1968fa"
                    >添加学生</a
                  >
                  <span style="color: #1968fa; padding: 0px 10px">|</span>
                  <i
                    class="el-icon-upload"
                    style="color: #1968fa; margin: 0px 5px"
                  ></i>
                  <a @click="handleOpenDialog" style="color: #1968fa"
                    >批量导入</a
                  >
                </span>
              </div>
              <el-divider></el-divider>
              <div class="search">
                <el-input
                  placeholder="请输入姓名"
                  v-model.trim="name"
                  class="input"
                  clearable
                >
                </el-input>
                <el-input
                  placeholder="请输入手机号"
                  v-model.trim="stunum"
                  class="input"
                  clearable
                >
                </el-input>
                <el-button
                  type="primary"
                  plain
                  @click="handleGetClassDetailsList(true)"
                  >查 询</el-button
                >
              </div>
            </div>
            <div class="bottom">
              <el-table
                :data="tableData"
                style="width: 100%; margin-top: 10px"
                :header-cell-style="{ background: '#E4EEFF', color: '#333333' }"
              >
                <el-table-column
                  prop="name"
                  label="姓名"
                  width="180"
                  align="center"
                >
                </el-table-column>
                <el-table-column prop="mobile" label="手机号" align="center">
                </el-table-column>
                <el-table-column label="性别" align="center">
                  <template slot-scope="scope">
                    {{
                      scope.row.sex
                        ? options.find((item) => item.value == scope.row.sex)
                            .label
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="280" align="center">
                  <template slot-scope="scope">
                    <span
                      style="margin: 0px 10px; color: #1968fa; cursor: pointer"
                      @click="handleOpenModifyStudent(false, scope.row)"
                      >修改</span
                    >
                    <span
                      style="margin: 0px 10px; color: #fa1900; cursor: pointer"
                      @click="handleConfirmDelete(scope.row)"
                      >刪除</span
                    >
                    <span
                      style="margin: 0px 10px; color: #1968fa; cursor: pointer"
                      @click="handleOpenModifyInfo('重置密码', scope.row)"
                      >重置密码</span
                    >
                  </template>
                </el-table-column>
                <div slot="empty" class="empty">
                  <el-empty description="暂无数据"></el-empty>
                </div>
              </el-table>
            </div>
            <div class="clearfix">
              <el-pagination
                class="pull-right"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5, 10, 20, 30, 40]"
                :page-size="pageSize"
                layout="total,prev,pager,next,sizes,jumper"
                :total="totalCount"
              ></el-pagination>
            </div>
          </div>
        </div>
      </div>
      <!-- footer页脚 -->
      <!-- <m-fotter /> -->
    </div>
    <!-- 修改班级信息/重置密码弹窗 -->
    <el-dialog
      :title="modifyDialogTitle"
      :visible.sync="modifyDialogVisible"
      width="500px"
    >
      <div class="input-box">
        <div class="dia-til">
          <span class="red">*</span
          >{{ modifyDialogTitle == "修改班级信息" ? "名称:" : "密码:" }}
        </div>
        <el-input
          v-if="modifyDialogTitle == '修改班级信息'"
          v-model.trim="modifyValue"
          placeholder="请输入班级名称"
        ></el-input>
        <el-input
          v-else
          v-model.trim="modifyValue"
          placeholder="请输入新密码"
        ></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          style="margin-right: 60px"
          @click="handleResetInfo"
          >确 定</el-button
        >
        <el-button @click="modifyDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 添加/修改学生 -->
    <el-dialog
      :title="studentDialogTitle"
      :visible.sync="studentDialogVisible"
      width="500px"
    >
      <div class="input-box">
        <div class="dia-til"><span class="red">*</span>姓名:</div>
        <el-input
          v-model.trim="studentName"
          placeholder="请输入学生姓名"
        ></el-input>
      </div>
      <div class="input-box">
        <div class="dia-til"><span class="red">*</span>手机号:</div>
        <el-input
          v-model.trim="stuNumber"
          placeholder="请输入手机号"
        ></el-input>
      </div>
      <div class="input-box">
        <div class="dia-til"><span class="red">*</span>性别:</div>
        <el-select
          v-model="sexValue"
          clearable
          placeholder="请选择"
          style="width: 100%"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div
        class="input-box"
        style="display: flex; flex-direction: column; align-items: flex-start"
      >
        <div style="color: red; margin-left: 35px; font-size: 16px">
          默认密码：123456
        </div>
        <div style="color: red; margin-left: 35px; font-size: 12px;margin-top:10px">
          注：金职母婴小程序，以下网址(www.jz1x.com),如有账户会统一重置成:123456
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          style="margin-right: 60px"
          @click="handleSubmitModifyStudent"
          >确 定</el-button
        >
        <el-button @click="studentDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 班级批量导入弹窗 -->
    <el-dialog
      title="学生批量导入"
      :visible.sync="moreImportdialogVisible"
      width="600px"
    >
      <div class="upload-box">
        <div class="upload-tip">
          导入数据需按模版填写信息,
          <span
            @click="handleImportTemplate('学生信息表', getExcelExport)"
            style="color: #409eff; cursor: pointer"
            >点击下载</span
          >
          <!-- <em
            @click="handleImportTemplate('学生信息表', getExcelExport)"
            style="color: #409eff"
            >点击下载</em
          > -->
        </div>
        <el-upload
          class="upload-demo"
          drag
          accept
          :headers="{ Authorization: $store.state.token }"
          :action="UPLOAD_URL"
          :on-success="handleSuccessUpload"
          :show-file-list="false"
          multiple
        >
          <div v-if="excelFileUrlShow">
            <img
              src="../../assets/images/excel.png"
              style="display: block; height: 100px; margin: 30px auto 10px"
            />
            <div style="color: #409eff">{{ filedata.name }}</div>
          </div>
          <div v-else>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">仅支持Excel文件 <em>点击上传</em></div>
          </div>
        </el-upload>
      </div>
      <div
        class="input-box"
        style="display: flex; flex-direction: column; align-items: flex-start;margin-top:10px;margin-left:68px"
      >
        <div style="color: red; margin-left: 35px; font-size: 16px">
          默认密码：123456
        </div>
        <div style="color: red; margin-left: 35px; font-size: 12px;margin-top:10px">
          注：金职母婴小程序，以下网址(www.jz1x.com),如有账户会统一重置成:123456
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmitList">导 入</el-button>
        <el-button @click="moreImportdialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 导入文件有误弹窗 -->
    <el-dialog
      :title="errExcelDialogTitle"
      :visible.sync="errExcelDialogVisible"
      width="500px"
    >
      <div
        v-for="item in errList"
        :key="item"
        style="padding: 10px 0px; color: red"
      >
        *{{ item }}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="errExcelDialogVisible = false" type="primary"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Base64 } from "js-base64";
import { STATUS_CODE_OK, UPLOAD_URL } from "@/config";
import { validationMobilePhone } from "@/utils/fromcheck.js";
import { handleImportTemplate } from "@/utils/index.js";
import { getExcelExport } from "@/api/addClass.js";
import {
  getClassDetailsList,
  resetPwd,
  updateStu,
  quitClass,
  saveStu,
  updateClass,
} from "@/api/personalCenter.js";
// import MHeader from "@/components/MHeader.vue";
// import MFotter from "@/components/MFotter.vue";
import MMenu from "@/components/MMenu.vue";
export default {
  name: "saveClass",
  data() {
    return {
      isPageShow: true, //页面是否显示
      tableData: [],
      name: "", // 学生名称-查询
      stunum: "", // 学生学号-查询
      id: "", // 班级id
      className: "", // 班级名称
      addId: "", // 添加时的id
      resetInfoItem: "", //重置密码/修改班级-单条数据
      studentItem: "", // 修改学生信息-单条数据
      modifyValue: "", // 修改班级/密码-弹窗
      modifyDialogVisible: false, //显示隐藏-修改班级信息/重置密码-弹窗
      modifyDialogTitle: "", //标题-修改班级信息/重置密码-弹窗
      studentDialogTitle: "", //标题-修改/添加学生信息-弹窗
      studentDialogVisible: false, // 显示隐藏-修改/添加学生信息-弹窗
      studentName: "", //学生姓名-弹窗
      stuNumber: "", // 学号-弹窗
      sexValue: "", // 性别
      isAdd: "", // 是否是新增弹窗
      options: [
        {
          value: "1",
          label: "男",
        },
        {
          value: "2",
          label: "女",
        },
        {
          value: "0",
          label: "保密",
        },
      ],
      currentPage: 1, // 页数
      pageSize: 5, // 条数
      totalCount: 0, // 总条数
      moreImportdialogVisible: false,
      handleImportTemplate,
      getExcelExport,
      UPLOAD_URL,
      excelFileUrlShow: false, //excel图标显示隐藏
      filedata: {}, //上传文件数据
      fileuplist: [],
      errList: [], // 错误路径
      errExcelDialogVisible: false, //excel有误信息弹窗显示隐藏
      errExcelDialogTitle: "批量导入有误信息列表", //excel有误信息弹窗标题
      tablesex: "",
    };
  },
  async created() {
    await this.handleLocalGetData();
    await this.handleGetClassDetailsList();
  },

  methods: {
    // 提交
    async handleSubmitList() {
      if (this.fileuplist.length < 1) {
        this.$notify({
          title: "提示",
          message: "请上传.xls文件后导入!",
          type: "warning",
        });
        return;
      }
      this.fileuplist.forEach((item) => {
        item.sex = this.options.find((fitem) => fitem.value == item.sex).value;
      });
      let datalsit = {
        classname: this.className,
        studentVOList: this.fileuplist,
      };
      let { data } = await saveStu(datalsit);
      if (data.code == STATUS_CODE_OK) {
        this.$notify({
          title: "成功",
          message: "批量导入成功!",
          type: "success",
        });
        this.moreImportdialogVisible = false;
        this.handleGetClassDetailsList();
      }
    },
    // 上传成功之后
    async handleSuccessUpload(res, file) {
      if (res.code == STATUS_CODE_OK) {
        this.$notify({
          title: "成功",
          message: "上传成功!",
          type: "success",
        });
        this.filedata = file;
        this.fileuplist = res.data;
        this.excelFileUrlShow = true;
      }
      if (res.msg == "导入内容错误") {
        this.errExcelDialogVisible = true;
        this.errList = res.data;
        return;
      }
      if (res.code == -1) {
        this.$notify({
          title: "提示",
          message: res.msg,
          type: "warning",
        });
        this.excelFileUrlShow = false;
        return;
      }
    },
    // 批量上传弹窗
    handleOpenDialog() {
      this.excelFileUrlShow = false;
      this.moreImportdialogVisible = true;
    },
    // 修改班级信息/重置密码
    handleOpenModifyInfo(dialogTitle, item = {}) {
      this.modifyDialogTitle = dialogTitle;
      if (this.modifyDialogTitle == "修改班级信息") {
        this.modifyValue = this.className;
      } else {
        this.modifyValue = "";
      }
      this.modifyDialogVisible = true;
      this.resetInfoItem = JSON.parse(JSON.stringify(item));
    },

    // 重置密码/修改班级信息提交
    async handleResetInfo() {
      let api = "";
      let datalist = {};
      if (this.modifyDialogTitle == "修改班级信息") {
        if (!this.modifyValue) {
          this.$notify({
            title: "提示",
            message: "请输入班级名称！",
            type: "warning",
          });
          return;
        }
        api = updateClass;
        datalist = {
          classId: this.id,
          className: this.modifyValue,
        };
      } else {
        if (!this.modifyValue) {
          this.$notify({
            title: "提示",
            message: "请输入重置密码！",
            type: "warning",
          });
          return;
        }
        api = resetPwd;
        datalist = {
          id: this.resetInfoItem.id,
          password: Base64.encode(this.modifyValue),
        };
      }

      let { data } = await api(datalist);
      if (data.code == STATUS_CODE_OK) {
        this.$notify({
          title: "成功",
          message: "修改成功!",
          type: "success",
        });
        this.handleGetClassDetailsList();
        this.modifyDialogVisible = false;
      }
    },

    // 打开添加/修改班级信息
    handleOpenModifyStudent(isAdd, item = {}) {
      this.studentItem = JSON.parse(JSON.stringify(item));
      // isAdd true为添加 false为修改
      this.isAdd = isAdd;
      if (this.isAdd) {
        this.studentDialogTitle = "添加学生";
        this.studentName = "";
        this.stuNumber = "";
        this.sexValue = "";
        this.addId = "";
      } else {
        this.studentDialogTitle = "修改学生";
        this.addId = this.studentItem.id;
        this.studentName = this.studentItem.name;
        this.stuNumber = this.studentItem.mobile;
        this.sexValue = this.options.find(
          (item) => this.studentItem.sex == item.value
        ).value;
      }
      this.studentDialogVisible = true;
    },

    // 添加/修改用户信息提交
    async handleSubmitModifyStudent() {
      if (!this.studentName) {
        this.$notify({
          title: "提示",
          message: "请输入姓名！",
          type: "warning",
        });
        return;
      }
      if (!this.stuNumber) {
        this.$notify({
          title: "提示",
          message: "请输入手机号！",
          type: "warning",
        });
        return;
      }
      if (!validationMobilePhone(this.stuNumber)) {
        this.$notify({
          title: "提示",
          message: "手机号格式错误！",
          type: "warning",
        });
        return;
      }
      if (!this.sexValue) {
        this.$notify({
          title: "提示",
          message: "请选择性别！",
          type: "warning",
        });
        return;
      }
      let api = saveStu;
      let datalsit = {
        classname: this.className,
        studentVOList: [
          {
            name: this.studentName,
            mobile: this.stuNumber,
            sex: this.sexValue,
          },
        ],
      };
      if (!this.isAdd) {
        api = updateStu;
        datalsit = {
          id: this.addId,
          name: this.studentName,
          mobile: this.stuNumber,
          sex: this.sexValue,
        };
      }
      let { data } = await api(datalsit);
      if (data.code == STATUS_CODE_OK) {
        this.handleGetClassDetailsList(true);
        this.$notify({
          title: "成功",
          message: "操作成功!",
          type: "success",
        });
      }
      this.studentDialogVisible = false;
    },

    // 是否确认删除
    async handleConfirmDelete(item) {
      try {
        await this.$confirm("此操作将删除该学生信息, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        this.handleDetelStudent(item);
      } catch {
        console.log("取消");
      }
    },

    // 删除学生
    async handleDetelStudent(item) {
      let { data } = await quitClass({
        userId: item.id,
        classId: this.id,
      });
      if (data.code == STATUS_CODE_OK) {
        this.handleGetClassDetailsList();
      }
    },

    // 获取本地基本详情数据
    handleLocalGetData() {
      if (this.$route.params.row) {
        sessionStorage.setItem("class", JSON.stringify(this.$route.params.row));
      }
      this.className = JSON.parse(sessionStorage.getItem("class")).name;
      this.id = JSON.parse(sessionStorage.getItem("class")).id;
    },

    // 获取班级详情信息
    async handleGetClassDetailsList(isReFresh = false) {
      if (isReFresh) {
        this.currentPage = 1;
      }
      let { data } = await getClassDetailsList({
        name: this.name,
        mobile: this.stunum,
        classId: this.id,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      });
      if (data.code == STATUS_CODE_OK) {
        this.tableData = data.data.records;
        this.totalCount = Number(data.data.total);
        this.className = data.data.classname;
      }
    },
    // 分页页数改变事件
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleGetClassDetailsList(true);
    },
    // 分页当前页改变事件
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handleGetClassDetailsList();
    },
  },
  components: {
    // MHeader,
    // MFotter,
    MMenu,
  },
};
</script>

<style scoped lang="scss">
$bg-color: #fff;
::v-deep .el-divider--horizontal {
  margin: 20px 0;
}
::v-deep .el-menu {
  min-height: 600px;
}
::v-deep .el-dialog__footer {
  display: flex;
  justify-content: space-evenly;
}
::v-deep .el-dialog__body {
  padding: 20px;
}
.input {
  width: 220px;
  margin-right: 20px;
}
.input-box {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}
.dia-til {
  width: 80px;
  text-align: right;
  margin-right: 10px;
  .red {
    color: red;
    margin-right: 5px;
  }
}
.upload-box {
  .upload-tip {
    margin-left: -130px;
    margin-bottom: 20px;
  }
  display: flex;
  flex-direction: column;
  align-items: center;
}
.dialog-box {
  .pdf-box {
    overflow-y: auto;
    max-height: 600px;
    display: flex;
    width: 600px;
    flex-direction: column;
    align-items: center;
    .pdf {
      width: 100%;
      border: 1px solid #000;
      margin-bottom: 10px;
    }
  }
  .dialog-video {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
  }
}
.wrap {
  background-color: $bg-color;
  .container {
    padding-bottom: 90px;
    .content {
      display: flex;
      margin-top: 30px;
      justify-content: space-between;
      .right-box {
        flex: 0.2;
        border-radius: 10px 10px 10px 10px;
        .el-menu {
          border-right: none;
        }
      }
      .left-box {
        flex: 0.8;
        margin: 0px 0px 0px 20px;
        padding: 0px 20px;
        box-sizing: border-box;
        background: #fff;
        border-radius: 10px 10px 10px 10px;
        .top {
          .input {
            width: 220px;
            margin-right: 20px;
          }
          .search {
            .label {
              margin-right: 20px;
            }
          }
          .import {
            margin-top: 20px;
            .label {
              margin-right: 20px;
            }
          }
          .title {
            padding-top: 20px;
            display: flex;
            justify-content: space-between;
          }
        }
        .bottom {
          .empty {
            height: 300px;
            padding: 50px;
            .text {
              color: red;
              cursor: pointer;
            }
          }
          .submit {
            width: 100%;
            display: flex;
            justify-content: space-evenly;
            .btn {
              width: 220px;
              margin-top: 20px;
            }
          }
        }
      }
    }
  }
}
</style>
